package com.dk.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class LoginController {

    @RequestMapping("toLogin")
    public String toLogin(){
        return "login";
    }

    @RequestMapping("login")
    public String login(String uname , String password, Model model){
        //使用shiro编写登录逻辑
        //1.获取subiect
        Subject subject = SecurityUtils.getSubject();
        //2.将参数封装成token对象
        UsernamePasswordToken token = new UsernamePasswordToken(uname,password);

        try {
            //3.执行登录逻辑
            subject.login(token); //帮我们执行登录逻辑
            return "redirect:/index"; //redirect:重定向
        }catch (UnknownAccountException e){//账号（用户）不存在
            model.addAttribute("message","账号不存在");
            return "login"; //账号不存在 返回登录
        }catch (IncorrectCredentialsException e){ //表示密码不正确
            model.addAttribute("message","密码错误");
            return "login";
        }

    }
}
